<template>
	<view>
		<canvas style="width:60px; height:60px;position: absolute; z-index: -10; left: -99999px; top: 0;" canvas-id="canvas"></canvas>
		<image :src="lwicon" mode="aspectFill" v-if="lwicon"></image>
		<image :src="textIcon" mode="aspectFill" v-else></image>
	</view>
</template>

<script>
	const COLORS = ['#CC9999', '#666699', '#FF9900', '#0099CC', '#CCCC99', '#CC3399', '#99CC00', '#FF6666',
     '#3399CC', '#CC6600', '#FF9933', '#009933','#FF6600',
       '#009966', '#CC6633', '#CC0066', '#009999', '#FFCC33', '#006699', '#FF9966',
       '#0066CC', '#339933', '#336699', '#99CC33', '#FF0033', '#333399', '#CCCC00',
        '#33CC99', '#990066', '#FFCC00', '#CC0033','#CC3366', '#663399', '#CC3333', '#003399'];
	// import imageUtil from '@/utils/imageUtil';
	export default {
		name: 'text-icon',
		data () {
			return {
				textIcon: ''
			};
		},
		props: {
			lwicon: String,
			lwtext: String
		},
		watch: {
			label: function (v) {
				this.genTextImg(v).then(res => {
					this.textIcon = res;
				});
			}
		},
		methods: {
			genTextImg(s, size = [60, 60]) {
				var vm = this;
				return new Promise((resolve) => {
					var text = s.slice(-2);
					var number = this.getNumber(text) % COLORS.length;
					let ctx = uni.createCanvasContext('canvas', vm);            
					ctx.setFillStyle(COLORS[number]);
					ctx.fillRect(0, 0, size[0], size[1]);
					ctx.setFillStyle('#fff');
					ctx.font = size[0]*0.6+"px Arial";
					ctx.setTextBaseline("middle");
					ctx.setTextAlign('center');
					if (text.length == 2) {
					ctx.font = size[0]*0.4+"px Arial";
					ctx.fillText(text,size[0]/2,size[1]/2); 
					} else {
						ctx.fillText(text,size[0]/2,size[1]/2);
					}
					ctx.draw(false, () => {
						setTimeout(() => {
							uni.canvasToTempFilePath({ // 保存canvas为图片
								canvasId: 'canvas',
								quality: 1,
								complete: function(res) {
									resolve(res.tempFilePath);
								} ,
							}, vm)
						}, 200);
					});
				});
			},

			getNumber(str) {
				var val = '';
				for (var i = 0; i < str.length; i++) {
					val += str.charCodeAt(i).toString(16);
				}
				return val.replaceAll(/[a-zA-Z]/g, '');
			}
		},
		mounted () {
			// debugger
			if (!this.lwicon && this.lwtext) {
				this.genTextImg(this.lwtext).then(res => {
					this.textIcon = res;
				});
			}
		},
		
	}
</script>

<style lang="scss" scoped>
    view {
        display: flex;
    }
</style>
